angular.module('inspinia', ['angularFileUpload']).controller('wechatPublicDetailCtrl', function ($scope, $http, SweetAlert, $state, $stateParams, i18nService, $timeout, FileUploader) {
  //数据源
  i18nService.setCurrentLang('zh-cn');


  $scope.titles = [{value: "", text: "请选择"}];
  $scope.pubNames = [{value: "", text: "请选择"}];
  $scope.batchInfo = {userType: ""};
  $scope.userType = angular.copy(initData.MSG_TO_USER_TYPE);
  $scope.userType.unshift({value: "", text: "请选择"});


  $scope.showImportModal = function () {
    $('#importModal').modal('show');
  };
  $scope.hideImportModal = function () {
    //删除批次和明细
    $scope.deleteBatch();
  };

  $scope.showPreSendModal = function () {
    $('#importModal').modal('hide');
    setTimeout(function () {
      $('#preSendModal').modal('show');
    }, 500)


  };
  $scope.hidePreSendModal = function () {
    $scope.deleteBatch();
    $('#preSendModal').modal('hide');
    // if (!$scope.toNext) {
    //   setTimeout(function () {
    //     $('#importModal').modal('show');
    //   }, 500)
    // }

  };


  /**
   * 删除批次和明细
   * @param id
   */
  $scope.deleteBatch = function () {
    if (!$scope.pushBatchNo) {
      return;
    }
    $http.post('publicAccountMsgBatch/delete?pushBatchNo=' + $scope.pushBatchNo,
      null, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .success(function (result) {
        if (result.status) {
          $('#importModal').modal('hide');
        } else {
          $scope.notice(result.msg);
        }
      }).error(function () {
      $scope.notice("系统异常！");
    });
  };

  /**
   * 获取模板明细
   * @param id
   */
  $scope.getInfoById = function () {
    $http.post('publicAccountMsgTemp/info?id=' + $stateParams.id,
      null, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
      .success(function (result) {
        if (result.status) {
          $scope.detailInfo = result.data;
          $scope.batchInfo.tempId = $scope.detailInfo.id;
        } else {
          $scope.notice(result.msg);
        }
      }).error(function () {
      $scope.notice("系统异常！");
    });
  };

  $scope.getInfoById();


  var opts = {info: null}
  if (_parameterName) {
    opts[_parameterName] = _token;
  }
  var uploader = $scope.uploader = new FileUploader({
    url: 'publicAccountMsgBatch/import',
    headers: {'X-CSRF-TOKEN': $scope.csrfData},
    formData: [opts],
    queueLimit: 1,   //文件个数
    removeAfterUpload: true  //上传后删除文件
  });
  //过滤长度，只能上传一个
  uploader.filters.push({
    name: 'isFile',
    fn: function (item, options) {
      return this.queue.length < 1;
    }
  });
  uploader.filters.push({
    name: 'imageFilter',
    fn: function(item,options) {
      if(item.size>10*1024*1024){
        return false;
      }
      return true;
    }
  });
  //过滤格式
  uploader.filters.push({
    name: 'fileFilter',
    fn: function(item /*{File|FileLikeObject}*/, options) {
      var type = '|' + item.name.slice(item.name.lastIndexOf('.') + 1) + '|';
      return '|xlsx|xls|'.indexOf(type) !== -1;
    }
  });
  uploader.removeFromQueue = function (value) {
    var index = this.getIndexOfItem(value);
    if (index >= 0) {
      var item = this.queue[index];
      if (item.isUploading) item.cancel();
      this.queue.splice(index, 1);
      item._destroy();
      this.progress = this._getTotalProgress();
    }
  };

  $scope.clearItems = function () {  //重新选择文件时，清空队列，达到覆盖文件的效果
    uploader.clearQueue();
  };

  $scope.submit = function () {
    var info = {
      tempId: $scope.detailInfo.id,
      userType: $scope.batchInfo.userType,
      msgContent: $scope.batchInfo.msgContent,
      msgUrl: $scope.batchInfo.msgUrl,
      msgRemark: $scope.batchInfo.msgRemark,
      effectiveStartTime: $scope.batchInfo.effectiveStartTime,
      effectiveEndTime: $scope.batchInfo.effectiveEndTime
    }
    if ($scope.batchInfo.userType != 'CUSTOM') {
      $scope.submitBatchInfo(info)
    } else {
      var fileNum = uploader.queue.length;
      if (fileNum < 1) {
        $scope.submitting = false;
        $scope.notice("上传的文件不能为空");
        return;
      }
      $scope.submitting = true;
      $scope.loadImg = true;
      //$("#coverbg").show();


      uploader.queue[0].formData[0].info = angular.toJson(info);
      uploader.uploadAll();//上传
      uploader.onSuccessItem = function (fileItem, response, status, headers) {//上传成功后的回调函数，在里面执行提交
        $scope.loadImg = false;
        //$("#coverbg").hide();
        $scope.submitting = false;
        if (response.status) {
          $scope.importResult = response.importResult;
          $scope.pushBatchNo = response.pushBatchNo;
          $scope.perSendInfo = response.info;
          $scope.toNext = response.toNext;
          if (response.toNext) {//失败数为0直接下一步
            $scope.showPreSendModal();
          } else {
            $scope.showImportModal();
          }
        } else {
          $scope.notice(response.msg);
        }
      };
      return false;
    }

  };


  /**
   * 提交公众号模板消息推送批次记录表
   */
  $scope.submitBatchInfo = function (info) {
    $scope.submitting = true;
    $http({
      url: 'publicAccountMsgBatch/save',
      method: 'POST',
      data: angular.toJson(info)
    }).success(function (result) {
      if (result.status) {
        $scope.submitting = false;
        $scope.perSendInfo = result.info;
        $scope.pushBatchNo = result.pushBatchNo;
        $scope.toNext = result.toNext;
        $scope.showPreSendModal();
      } else {
        $scope.submitting = false;
        $scope.notice(result.msg);
      }
    });

  }

  $scope.send = function () {
    $scope.submitting = true;
    $http({
      url: 'publicAccountMsgBatch/send/' + $scope.pushBatchNo,
      method: 'Get',
    }).success(function (result) {
      if (result.status) {
        $scope.submitting = false;
        $('#preSendModal').modal('hide');
        setTimeout(function () {
          $state.transitionTo('sys.wechatPublic', null, {reload: false});
        }, 500)

        $scope.notice(result.msg);
      } else {
        $scope.submitting = false;
        $scope.notice(result.msg);
      }
    });
  }

});

